package com.yanqu.road.server.manger;

import com.yanqu.road.entity.servercenter.ServerInfo;
import com.yanqu.road.logic.bussiness.config.LanguageBussiness;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.utils.ConfigHelper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.Map;

public class ServerLanguageMgr extends TempMgr {

    private static Logger logger = LogManager.getLogger(ServerLanguageMgr.class.getName());

    private static Map<String, Map<String, String>> languageMap;

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean stop() {
        return true;
    }

    @Override
    public boolean reloadData() {
        reloadLanguage();
        return true;
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    public static void reloadLanguage(){
        long serverId = ConfigHelper.getInt("serverId");
        int channelId = 0;
        ServerInfo serverInfo = ServerListMgr.getServerInfo(serverId);
        if(null != serverInfo){
            channelId = serverInfo.getChannelId();
        }
        if(channelId == 0 && !"1".equals(ConfigHelper.getValue("isUserCenter"))){
            channelId = ConfigHelper.getInt("channelId");
        }
        //新加了渠道语言表，覆盖掉原先的表
        languageMap = mergeLanguage(LanguageBussiness.getServerLanguageMap(),LanguageBussiness.getServerLanguageMapChannel(channelId));
    }

    private static Map<String, Map<String, String>> mergeLanguage(Map<String, Map<String, String>> oldMap , Map<String, Map<String, String>> channelMap){
        for(String key : channelMap.keySet()){
            Map<String, String> temp = channelMap.get(key);
            oldMap.put(key,temp);
        }
        return oldMap;
    }

    public static String getContent(String key, String language) {
        if (languageMap == null) {
//            logger.info("languageMap is null, key:{}, language:{}", key, language);
            return key;
        }
        if (!languageMap.containsKey(key)) {
//            logger.info("not this key,  key:{}, language:{}.", key, language);
            return key;
        }
        if (!languageMap.get(key).containsKey(language)) {
//            logger.info("not this language,  key:{}, language:{}.", key, language);
            return key;
        }

        if (languageMap.get(key).get(language) == null) {
//            logger.info("text is null,  key:{}, language:{}.", key, language);
            return key;
        }

        return languageMap.get(key).get(language);
    }
}
